<template>
    <div>
        <div class="post-list">
            <!-- <div class="publish-btn" @click="handleAdd">
                <el-icon><EditPen /></el-icon>
                <div>发布</div>
            </div> -->
            <div class="search-div">
              <el-button type="info"  icon="Edit" @click="handleAdd()" style="background-color:#2a5caa;">发布帖子</el-button>
              <el-button type="info"  icon="Document" @click="toMyBlog()" style="background-color:#c63c26;">我的帖子</el-button>
            </div>
            <el-card v-for="post in articles" :key="post.id" class="post-card">
                <div class="post-header" @click="toDetailPage(post.id)">
                    <el-avatar :src="post.user.pic" class="post-avatar"></el-avatar>
                    <div class="post-user-info">
                    <span class="post-username">{{ post.user.nickName }}</span>
                    <span class="post-time">发布时间： {{ timestampToDayHM(post.updatedAt) }}</span>
                    </div>
                </div>
                <div class="post-content">
                    <div @click="toDetailPage(post.id)">{{ post.content }}</div>
                    <el-image
                        class="post-image"
                        style="width:100px; height:100px;"
                        v-for="(image, index) in post.picList" 
                        :key="index"
                        :src='image'
                        :zoom-rate="1.2"
                        :max-scale="7"
                        :min-scale="0.2"
                        :preview-src-list="post.picList"
                        show-progress
                        fit="cover"
                    />
                </div>
                <div class="post-actions">
                    <el-button v-if="post.isLiked" type="primary" icon="ArrowUpBold" @click="toggleLike(-1, post)">
                        {{ post.likes }}点赞
                    </el-button>
                    <el-button v-else type="primary" plain icon="ArrowUpBold" @click="toggleLike(1, post)">
                        {{ post.likes }}点赞
                    </el-button>
                    <el-button type="danger" plain icon="ChatLineSquare" @click="toDetailPage(post.id)">
                        {{ post.commentCount }} 评论
                    </el-button>
                </div>
            </el-card>
            <div class="pag">
              <!-- 分页组件 -->
              <el-pagination background layout="prev, pager, next" v-model:page-size="queryForm.pageSize" v-model:current-page="queryForm.pageNo" :total="total" @current-change="getInfo" />
            </div>
        </div>
        <el-dialog v-model="open" title="发布帖子" width="780px" append-to-body>
            <el-form ref="formRef" label-width="80px" :status-icon="true" :model="editForm" :rules="rules">
            <el-form-item prop="mobile" label="帖子内容">
                <el-input v-model="editForm.content" placeholder="请输入帖子内容" autocomplete="off" type="textarea" :rows="6"></el-input>
            </el-form-item>
            <el-form-item label="附加图片" prop="role">
                <el-upload 
                    class="avatar-uploader showUploader"
                    ref="businessLicense"
                    action
                    multiple
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :on-change="uploadSectionFile"
                    :limit="6"
                >
                    <ul class="img-list">
                    <li v-for="(pic,i) in pics" :key="i" class="img-li" onclick="(function(e){e.stopPropagation()}(event))">
                        <img :src="pic" class="avatar aspect-fill" style="width: 200px;height: 160px;"/>
                        <i class="logo-remove el-icon-delete" @click="handleRemovePics(i)" ><el-icon><Delete /></el-icon></i>
                    </li>
                    <li v-if="pics.length==0 || pics.length<6" class="addpic avatar-uploader-icon"><el-icon><Plus /></el-icon></li>
                    </ul>
                </el-upload>
            </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup lang="ts">
  import { ref, reactive, nextTick, toRef } from "vue";
  import baseService from "@/service/baseService";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
  import { fileUploader } from '@/utils/upload.js'
  import { useRouter, useRoute } from 'vue-router';
import func from "vue-temp/vue-editor-bridge";
  
  const router = useRouter();
  const route = useRoute();
  // 查询参数
  const queryForm = reactive({
    deptName: "",
    pageNo: 1,
    pageSize: 10
  });
  // 列表内容数量
  const total = ref(0);
  // 列表是否加载
  const loading = ref(true);

  // 资讯数据
  const articles = ref<any>([]);

  // 表单实例
  const formRef = ref();
  // 是否打开弹出框
  const open = ref(false);
  const openDetail = ref(false);
  const pics = ref<any>([])

  // 跳转到资讯详情页面
  const toDetailPage = (pid: number)=>{
    router.push("/blog/detail?nid="+pid);
  }

  // 提交表单数据
  let editForm = toRef(
    reactive({
        pics: '',
        content: '',
    })
    );
    // 表单验证
    const rules = ref({
        content: [{ required: true, message: "请输入", trigger: "blur" }],
    });

    /**
     * 表单重置
     */
    function reset() {
        editForm.value = {
            pics: '',
            content: '',
        };
        pics.value = []
        nextTick(() => {
            formRef.value?.resetFields();
        });
    }

    /**
     * 修改按钮操作
     * @param id 主键
     */
    function handlePublish() {
        open.value = true;
        reset()
        nextTick(() => {
            formRef.value?.resetFields();
        });
    }

  const getInfo = () => {
    const cid = route.query.cid
    console.log('从路由获取参数：', route.query)
    let req = {category: cid}
    baseService.post(`/api/note/list`, req).then((res) => {
      console.log('获取列表：',res)
      articles.value = res.data.records;
      total.value = res.data.totalrecord;
      loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
  }

   // 图片上传
function uploadSectionFile(file: any) {
  console.log('选定图片！',file)
  const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
  const isJPG = typeArr.indexOf(file.raw.type) !== -1;
  const isLt3M = file.size / 1024 / 1024 < 3;
  if (!isJPG) {
    // ElMessage.error("只能是图片!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  if (!isLt3M) {
    // ElMessage.error("上传图片大小不能超过 3MB!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  // FormData 对象
  var formData = new FormData();
  // 文件对象
  formData.append("myFile", file.raw)
  console.log('上传图片表单：', formData)
  fileUploader(formData).then((res) => {
    if (res.data.errno==0) {
      //this.photoObj = res.data.data.objectId;
      console.log('图片上传成功！', res.data)
      pics.value.push(res.data.data);
    } else {
      // ElMessage.error(res.data.message);
    }
  })
}

function handlePreview(file: any) {
    console.log(file);
}
function handleRemove(file: any, fileList: any) {
  alert('移除')
    //return this.$confirm(`确定移除 ${file.name}？`);
}
// 移除多图中的其中一张
function handleRemovePics(idx: number){
  console.log('移除图片下标为：', idx)
  pics.value.splice(idx, 1);
}

/**
 * 提交按钮
 */
 function submitForm() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return;
    console.log('图片字段', pics.value)
    editForm.value.pics = pics.value.join(',')
    baseService.post(`/api/note/save`, editForm.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        open.value = false;
        getInfo();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

//点赞
const toggleLike = (count: number, note: any) => {
    const pid = note.id
    baseService.get(`/api/note/like/${pid}`).then((res) => {
      loading.value = false;
      if(count==1){
        note.isLiked=1
        note.likes++
        ElMessage.success('点赞成功')
      }else{
        note.isLiked=0
        note.likes--
        ElMessage.warning('已取消点赞')
      }
    }).catch(() => {
        loading.value = false;
    });
  }

/**
 * 新增按钮操作
 */
 function handleAdd() {
  reset();
  open.value = true;
}

function toMyBlog(){
  router.push("/user/my/blog");
}

  getInfo()

</script>

<style scoped>
.post-list {
    padding: 20px;
  max-width: 920px;
  margin: 0 auto;
}

.publish-btn{
    float: right;
    background-color: #d98481;
    color: #fff;
    width: 50px;
    height: 50px;
    text-align: center;
    border-radius: 25px;
    padding-top: 2px;
    cursor: pointer;
}
.publish-btn:hover{
    background-color: #e2645f;
}
.publish-btn .el-icon{
    font-size: 20px;
}

.post-card {
  margin-bottom: 20px;
  width: 825px;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  cursor: pointer;
}

.post-avatar {
  margin-right: 10px;
}

.post-user-info {
  display: flex;
  flex-direction: column;
}

.post-username {
  font-weight: bold;
}

.post-time {
  font-size: 12px;
  color: #999;
  padding-top: 5px;
}

.post-content {
  margin-bottom: 10px;
  cursor: pointer;
  line-height: 24px;
}

.post-image {
  width: 100%;
  margin: 10px 10px 0 0;
}

.post-actions {
  display: flex;
  justify-content: flex-start;
}

.el-button {
  margin-right: 10px;
}
.addpic{
font-size: 22px;
padding: 20px 25px 15px 25px;
border: 2px dashed #ccc;
color: #888;
height: 68px;
}
.img-list{
display: flex;
flex-wrap: wrap;
}
.img-list .img-li{
width: 260px;
position: relative;
margin-right: 10px;
}
.logo-remove{
font-size: 22px;
position: absolute;
top: 10px;
right: 10px;
color: #f00;
cursor: pointer;
text-shadow: #000 4px 4px 5px;
}
.logo-remove .el-icon{
box-shadow: #fff 3px 5px 6px;
background-color: #fff;
}
.logo-remove:HOVER{
color: #F56C6C;
}
.search-div{
  margin-bottom: 15px;
}
.pag{
  margin-top: 30px;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
</style>